<!--
 * @Descripttion: 新增房间-组件
 * @version: 1.0
 * @Author: 狸猫
 * @Date: 2023-10-26 17:16:01
 * @LastEditors: 狸猫
 * @LastEditTime: 2024-04-18 17:32:29
-->
<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1200px"
      append-to-body
      :before-close="close"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-descriptions title="房源信息"> </el-descriptions>
        <div class="form">
          <el-form-item label="楼盘" prop="estateId">
            <!-- v-if重新渲染解决不回显问题 -->
            <!-- <el-cascader
              v-if="reRender"
              ref="areaPicker"
              v-model="form.region"
              :props="areaProps"
              :show-all-levels="false"
              @change="handleChangeArea"
            ></el-cascader> -->
            <el-input
              style="width: 160px; margin-right: 10px"
              v-model="form.estateName"
              placeholder="请选择楼盘"
              readonly
            ></el-input>
            <el-button
              type="primary"
              icon="el-icon-office-building"
              @click="dialogEstate = true"
              size="small"
              >选择楼盘</el-button
            >
          </el-form-item>
          <el-form-item label="楼栋、单元" label-width="130" prop="houseInfo">
            <el-cascader
              v-model="form.houseInfo"
              ref="houseInfo"
              :props="{
                value: 'id',
                label: 'name',
              }"
              :options="estateList"
              @change="handleChange"
              @visible-change="checkedRegion"
            >
            </el-cascader>
          </el-form-item>
          <el-form-item label="所在楼层" prop="floors">
            <el-select
              v-model="form.floors"
              placeholder="请选择"
              @visible-change="checkedHouseInfo"
            >
              <el-option
                v-for="dict in floorList"
                :key="dict.value"
                :label="dict"
                :value="dict"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="房屋类型" prop="houseNature">
            <el-select
              v-model="form.houseNature"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="dict in dict.type.dict_house_nature"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="房型类型" prop="houseType">
            <el-select v-model="form.houseType" placeholder="请选择" clearable>
              <el-option
                v-for="dict in dict.type.dict_house_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="房间号" prop="roomNumber">
            <el-input v-model="form.roomNumber" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="面积" prop="houseArea">
            <el-input
              type="number"
              v-model="form.houseArea"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="户型" prop="roomType">
            <!-- <el-select v-model="form.roomType" placeholder="请选择" clearable>
              <el-option
                v-for="dict in dict.type.dict_room_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select> -->
            <el-input
              type="number"
              v-model.number="form.roomType"
              placeholder="请输入"
            >
          <span slot="append">室</span>
          </el-input>
          </el-form-item>
          <el-form-item label="朝向" prop="houseOrientation">
            <el-select v-model="form.houseOrientation" placeholder="请选择" clearable>
              <el-option
                v-for="dict in dict.type.house_orientation"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            <!-- <el-input v-model="form.houseOrientation" placeholder="请输入" /> -->
          </el-form-item>
        </div>
        <el-descriptions title="附加信息"> </el-descriptions>
        <div class="form">
          <el-form-item label="水表号" prop="waterMeterNumber">
            <el-input
              type="number"
              v-model="form.waterMeterNumber"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="电表号" prop="electricMeterNumber">
            <el-input
              type="number"
              v-model="form.electricMeterNumber"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="燃气表号" prop="gasMeterNumber">
            <el-input
              type="number"
              v-model="form.gasMeterNumber"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item
            label="是否为智能设备"
            label-width="100"
            prop="smartFurnitureType"
          >
            <el-radio-group v-model="form.smartFurnitureType">
              <el-radio label="0">否</el-radio>
              <el-radio label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="房屋二维码" label-width="100" prop="houseQrCode">
            <el-upload
              class="avatar-uploader"
              action="/api/common/upload"
              :show-file-list="false"
              :auto-upload="true"
              :headers="headers"
              :on-success="onSuccess"
              :on-remove="onRemove"
              :accept="'image/*'"
            >
              <img
                v-if="form.houseQrCode"
                :src="form.houseQrCode"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </div>
        <el-descriptions title="出租信息"> </el-descriptions>
        <div class="form">
          <el-form-item
            label="是否线上出租"
            label-width="100"
            prop="onlineRentalType"
          >
            <el-radio-group v-model="form.onlineRentalType">
              <el-radio
                v-for="dict in dict.type.dict_online_rental_type"
                :key="dict.value"
                :label="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否合租" label-width="100" prop="estateType">
            <el-radio-group v-model="form.shareFlatType">
              <el-radio label="0">否</el-radio>
              <el-radio label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <el-descriptions title="房源归属"> </el-descriptions>
        <div class="form">
          <el-form-item label="产权类型" prop="housePropertyType">
            <el-select
              v-model="form.housePropertyType"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="dict in []"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="产权所有人" label-width="120px" prop="housePropertyOwner">
            <el-select
              v-model="form.housePropertyOwner"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="dict in []"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="房屋管理员" label-width="120px" prop="houseManagerId">
            <el-select
              v-model="form.houseManagerId"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="dict in []"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="关联物业" prop="propertyId">
            <el-select v-model="form.propertyId" placeholder="请选择">
              <el-option
                v-for="item in []"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-descriptions title="房屋设施"> </el-descriptions>
        <el-button
          style="margin-bottom: 10px"
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="addfacilities"
          >新增</el-button
        >

        <!-- <el-row
          :gutter="6"
          v-for="(item, index) in form.facilitiesItemList"
          :key="index"
          style="margin-bottom: 10px"
        >
          <el-col :span="6">
            <el-form-item
              label="房屋设施"
              :prop="'facilitiesItemList.' + index + '.facilitiesId'"
              :rules="[
                {
                  required: true,
                  message: '请选择房屋设施',
                  trigger: 'change',
                },
              ]"
            >
              <el-select
                v-model="item.facilitiesId"
                placeholder="请选择房屋设施"
              >
                <el-option
                  v-for="(facility, index) in facilitiesMap"
                  :key="index"
                  :label="facility.facilitiesName"
                  :value="facility.facilitiesId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="display: flex; align-items: center">
            <el-form-item
              label="数量"
              :prop="'facilitiesItemList.' + index + '.facilitiesNumber'"
              :rules="[
                {
                  required: true,
                  message: '请输入数量',
                  trigger: 'change',
                },
              ]"
            >
              <el-input
                v-model.number="item.facilitiesNumber"
                placeholder="请输入"
                type="number"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="display: flex; align-items: center">
            <el-form-item
              label="单价"
              :prop="'facilitiesItemList.' + index + '.facilitiesPrice'"
              :rules="[
                {
                  required: true,
                  message: '请输入单价',
                  trigger: 'blur',
                },
              ]"
            >
              <el-input
                v-model.number="item.facilitiesPrice"
                placeholder="请输入"
                type="number"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1" style="display: flex; align-items: center">
            <i
              class="el-icon-remove-outline"
              style="
                color: #e63f32;
                font-size: 24px;
                margin-left: 20px;
                margin-top: 6px;
                cursor: pointer;
              "
              @click="delfacilities(index)"
            ></i>
          </el-col>
        </el-row> -->
        <el-table :data="form.facilitiesItemList" style="width: 100%">
          <el-table-column prop="name" label="设施名称">
            <template slot-scope="scope">
              <el-form-item
                label=""
                label-width="0"
                :prop="'facilitiesItemList.' + scope.$index + '.facilitiesId'"
                :rules="[
                  {
                    required: true,
                    message: '请选择房屋设施',
                    trigger: 'change',
                  },
                ]"
              >
                <el-select
                  v-model="form.facilitiesItemList[scope.$index].facilitiesId"
                  placeholder="请选择房屋设施"
                >
                  <el-option
                    v-for="(facility, index) in facilitiesMap"
                    :key="index"
                    :label="facility.facilitiesName"
                    :value="facility.facilitiesId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="amount1" label="数量">
            <template slot-scope="scope">
              <el-form-item
                label-width="0"
                label=""
                :prop="
                  'facilitiesItemList.' + scope.$index + '.facilitiesNumber'
                "
                :rules="[
                  {
                    required: true,
                    message: '请输入数量',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input
                  v-model.number="
                    form.facilitiesItemList[scope.$index].facilitiesNumber
                  "
                  placeholder="请输入"
                  type="number"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="amount2" label="单价">
            <template slot-scope="scope">
              <el-form-item
                label=""
                label-width="0"
                :prop="
                  'facilitiesItemList.' + scope.$index + '.facilitiesPrice'
                "
                :rules="[
                  {
                    required: true,
                    message: '请输入单价',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input
                  v-model.number="
                    form.facilitiesItemList[scope.$index].facilitiesPrice
                  "
                  placeholder="请输入"
                  type="number"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="danger"
                size="mini"
                style="margin-bottom: 22px"
                @click="delfacilities(scope.$index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <selectEstate v-model="dialogEstate" @success="successHandel" />
  </div>
</template>
<script>
function filterUnit(id, arr) {
  for (const item of arr) {
    if (item.id == id) return item;
    if (item.children && item.children.length > 0) {
      const _item = filterUnit(id, item.children);
      if (_item) return _item;
    }
  }
}
import { listFacilities } from "@/api/house/unmount";
import { addRoom, getRoom, updateRoom } from "@/api/house/room";
import { listArea } from "@/api/system/config";
import { listEstateArray, listBuildingArray } from "@/api/house/estate";
import { getToken } from "@/utils/auth";
import selectEstate from "@/components/selectEstate/select-estate.vue";
export default {
  name: "roomAdd",
  dicts: [
    "dict_house_nature",
    "dict_house_type",
    "dict_online_rental_type",
    "dict_room_type",
    "house_orientation"
  ],
  components: { selectEstate },
  props: {
    open: {
      type: Boolean,
      default: false,
    },
    roomId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      dialogEstate: false,
      reRender: false,
      headers: {
        Authorization: `Bearer   ` + getToken(),
      },
      floorList: [],
      //楼盘列表
      estateList: [],
      areaOptions: [],
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      form: {
        floors: "",
        estateId: "",
        facilitiesItemList: [],
        subordinateHouseList: [],
        roomNumber: null,
        onlineRentalType: "0",
        shareFlatType: "0",
        smartFurnitureType: "0",
        housePropertyType: null,
        houseOrientation: null,
        roomType: null,
        houseManagerId: null,
        propertyId: null,
        region: [],
        houseInfo: [],
      },
      areaProps: {
        lazy: true,
        // emitPath: false,
        lazyLoad(node, resolve) {
          listArea({ level: node.level + 1, parentId: node.value }).then(
            (res) => {
              const areas = res.data.map((value, i) => ({
                value: value.id,
                label: value.name,
                leaf: node.level >= 4,
              }));
              resolve(areas);
            }
          );
        },
      },
      rules: {
        region: [{ required: true, message: "请选择地区", trigger: "change" }],
        estateId: [
          { required: true, message: "请选择楼盘", trigger: "change" },
        ],
        houseInfo: [
          {
            required: true,
            message: "请选择楼栋、单元",
            trigger: "change",
          },
        ],
        houseNature: [
          { required: true, message: "请选择房屋类型", trigger: "change" },
        ],
        houseType: [
          { required: true, message: "请选择房型类型", trigger: "change" },
        ],
        onlineRentalType: [
          { required: true, message: "请选择是否线上出租", trigger: "change" },
        ],
        roomNumber: [
          { required: true, message: "请输入房间号", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
        houseArea: [{ required: true, message: "请输入面积", trigger: "blur" }],
        roomType: [
          { required: true, message: "请选择户型", trigger: "change" },
        ],
        houseOrientation: [
          { required: true, message: "请输入朝向", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
        housePropertyType: [
          { required: false, message: "请选择产权类型", trigger: "change" },
        ],
        housePropertyOwner: [
          { required: false, message: "请选择产权所有人", trigger: "change" },
        ],
        smartFurnitureType: [
          {
            required: true,
            message: "请选择是否为智能设备",
            trigger: "change",
          },
        ],
        houseManagerId: [
          { required: false, message: "请选择房屋管理员", trigger: "change" },
        ],
        propertyId: [
          { required: false, message: "请选择关联物业", trigger: "change" },
        ],
        floors: [{ required: true, message: "请选择楼层", trigger: "change" }],
      },
      title: "新增房间",
      file: "",
    };
  },
  async created() {
    this.getfacilityList();
    if (this.roomId) {
      this.getRoomDetail();
      this.title = "编辑房间";
    } else {
      this.reRender = true;
    }
  },
  methods: {
    successHandel(item) {
      this.form.estateId = item.estateId;
      this.form.estateName = item.estateName;
      this.getlistBuilding();
    },
    handleChange(e) {
      const checkedNodes = this.$refs["houseInfo"].getCheckedNodes();
      const ids = checkedNodes[0].path;
      const labels = checkedNodes[0].pathLabels;
      let floorList = [];
      let number = checkedNodes[0].data.number;
      let i = 1;
      while (i <= number) {
        floorList.push(i);
        i++;
      }
      this.floorList = floorList;
      //this.form.estateId = ids[0];
      //this.form.estateName = labels[0];
      this.form.buildingId = ids[0];
      this.form.buildingName = labels[0];
      this.form.unitId = ids[1];
      this.form.unitName = labels[1];
    },
    //检测是否选择区域
    checkedRegion(e) {
      if (this.form.estateId == "" && e) {
        this.$modal.closeAll();
        this.$modal.msgError("请先选择楼盘");
      }
    },
    checkedHouseInfo(e) {
      if (this.form.houseInfo.length == 0 && e) {
        this.$modal.closeAll();
        this.$modal.msgError("请先选择楼栋、单元");
      }
    },
    estateChange(e) {
      let data = this.estateList.find((item) => item.estateId === e);
      this.form.estateName = data.estateName;
    },

    /** 详情 */
    async getRoomDetail() {
      this.loading = true;
      await getRoom(this.roomId).then((response) => {
        let form = response.data;
        // let region = [];
        // region.push(response.data.provinceId);
        // region.push(response.data.cityId);
        // region.push(response.data.districtId);
        // region.push(response.data.streetId);
        // region.push(response.data.communityId);
        let houseInfo = [];
        houseInfo.push(response.data.buildingId);
        houseInfo.push(response.data.unitId);
        //form.region = region;
        form.houseInfo = houseInfo;
        this.form = form;
        this.reRender = true;
      });
      await this.getlistBuilding();
    },
    /** 查询楼盘列表 */
    getlistEstate() {
      this.loading = true;
      listEstateArray({ communityId: this.form.region[4] }).then((response) => {
        this.estateList = response;
        if (this.form.unitId) {
          let data = filterUnit(this.form.unitId, this.estateList);
          let floorList = [];
          let number = data.number;
          let i = 1;
          while (i <= number) {
            floorList.push(i);
            i++;
          }
          this.floorList = floorList;
        }
      });
    },
    /** 查询楼栋、单元集合 */
    getlistBuilding() {
      this.loading = true;
      listBuildingArray({ estateId: this.form.estateId }).then((response) => {
        this.estateList = response;
        if (this.form.unitId) {
          let data = filterUnit(this.form.unitId, this.estateList);
          let floorList = [];
          let number = data.number;
          let i = 1;
          while (i <= number) {
            floorList.push(i);
            i++;
          }
          this.floorList = floorList;
        }
      });
    },
    //区域选择
    handleChangeArea(val) {
      const checkedNode = this.$refs["areaPicker"].panel.getNodeByValue(val);
      const ids = checkedNode.path;
      const labels = checkedNode.pathLabels;
      this.form.provinceId = ids[0];
      this.form.cityId = ids[1];
      this.form.districtId = ids[2];
      this.form.streetId = ids[3];
      this.form.communityId = ids[4];

      this.form.provinceName = labels[0];
      this.form.cityName = labels[1];
      this.form.districtName = labels[2];
      this.form.streetName = labels[3];
      this.form.communityName = labels[4];
      this.form.estateId = "";
      this.getlistEstate();
      this.form.houseInfo = [];
    },

    //删除设施
    delfacilities(index) {
      this.form.facilitiesItemList.splice(index, 1);
    },
    //添加设施
    addfacilities() {
      this.form.facilitiesItemList.push({
        facilitiesId: null,
        facilitiesNumber: null,
        facilitiesPrice: null,
        facilitiesState: 1,
      });
    },
    /** 查询设施列表 */
    getfacilityList() {
      listFacilities().then((response) => {
        this.facilitiesMap = response.data;
      });
    },
    onSuccess(response, file, fileList) {
      this.$set(this.form, "houseQrCode", response.url);
      //this.form.houseQrCode = response.url;
    },
    onRemove() {
      this.form.houseQrCode = "";
    },
    handleRemove(file) {
      console.log(file);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.roomId != "") {
            updateRoom(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.close();
            });
          } else {
            addRoom(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.close();
            });
          }
        }
      });
    },
    cancel() {
      this.close();
    },
    close() {
      this.$emit("closeeldialog");
    },
  },
};
</script>
<style lang="scss" scoped>
.form {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}
.el-input::v-deep {
  width: 217px;
}
.avatar-uploader::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader::v-deep .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
